<template>
    <div class="about">
        <!-- 查询区----start -->
        <el-form  :inline="true" ref="formSearch" :model="formSearch" class="demo-form-inline">
            <el-form-item label="店铺名">
                  <el-select v-model="formSearch.shopId" placeholder="请选择">
                     <el-option
                        v-for="item in testData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="优惠券类型">
            <el-select v-model="formSearch.type" placeholder="请选择">
                <el-option
                        v-for="item in option1"    
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
            </el-select>
            </el-form-item>
              <el-form-item label="优惠券名称">
                <el-input v-model="formSearch.name" placeholder="请输入优惠券名称"></el-input>
            </el-form-item>
            <el-form-item label="使用平台">
                <el-select v-model="formSearch.platform" placeholder="请选择">
                     <el-option
                        v-for="item in option2"    
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="使用门槛">
                <el-input v-model="formSearch.minPoint" placeholder="输入金额"></el-input>
            </el-form-item>
            <el-form-item label="开始日期">
                <el-date-picker
                   v-model="formSearch.startTime"
                   type="date"
                   placeholder="选择上线日期时间"
                   align="right"
                   :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期">
                <el-date-picker
                   v-model="formSearch.endTime"
                   type="date"
                   placeholder="选择上线日期时间"
                   align="right"
                   :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="使用类型">
                <el-select v-model="formSearch.useType" placeholder="请选择">
                      <el-option
                        v-for="item in option3"    
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="操作" style="margin-left:50px;">
                <el-button type="primary"  icon="el-icon-search" @click="loadData()">查询</el-button>
                <el-button type="warning" icon="el-icon-refresh-right plain" @click="formSearch={}">重置</el-button>
                <el-button type="primary" icon="el-icon-circle-plus"  @click="addbtn()">添加</el-button>
            </el-form-item>
        </el-form>
        <!-- 查询区----end -->
        <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
            prop="shopId"
            label="店铺名">
             <template slot-scope="scope" >
              <div v-for="item in testData" :key="item.id">
                <div v-if="item.id==scope.row.shopId">
                  {{ item.name}}
                </div>
              </div>
             </template>
        </el-table-column>
        <el-table-column
            prop="type"
            label="优惠券类型">
            <template slot-scope="scope">
                {{scope.row.type | type()}}
            </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="优惠券名称">
        </el-table-column>
        <el-table-column
            prop="platform"
            label="使用平台">
             <template slot-scope="scope">
                {{scope.row.platform | platform()}}
            </template>
        </el-table-column>
        <el-table-column
            prop="count"
            label="数量">
        </el-table-column>
         <el-table-column
            prop="amount"
            label="金额">
        </el-table-column>
        <el-table-column
            prop="perLimit"
            label="每人限领张数">
        </el-table-column>
          <el-table-column
            prop="minPoint"
            label="使用门槛">
            <template slot-scope="scope">
                {{ scope.row.minPoint==0 ? "无门槛" : scope.row.minPoint }}
            </template>
        </el-table-column>     
        <el-table-column
            prop="startTime"
            label="开始时间">
            <template slot-scope="scope">
                {{scope.row.startTime | dateFilter("yyyy-mm-dd")}}
            </template>
        </el-table-column>
         <el-table-column
            prop="endTime"
            label="结束时间">
            <template slot-scope="scope">
                {{scope.row.endTime | dateFilter("yyyy-mm-dd")}}
            </template>
        </el-table-column>
        <el-table-column
            prop="useType"
            label="使用类型">
            <template slot-scope="scope">
                {{scope.row.useType | useType()}}
            </template>
        </el-table-column>
        <el-table-column
            prop="note"
            label="备注">
        </el-table-column>
        <el-table-column
            prop="publishCount"
            label="发行数量">
        </el-table-column>
        <el-table-column
            prop="useCount"
            label="已使用数量">
        </el-table-column>
        <el-table-column
            prop="receiveCount"
            label="领取数量">
        </el-table-column>
        <el-table-column
            prop="enableTime"
            label="领取截止日期">
            <template slot-scope="scope">
                {{scope.row.enableTime | dateFilter("yyyy-mm-dd")}}
            </template>
        </el-table-column>
        <el-table-column
            prop="code"
            label="优惠码">
        </el-table-column> 
        <el-table-column
            prop="memberLevel"
            label="可领取的会员类型">
            <template slot-scope="scope" >
              <div v-for="item in testData2" :key="item.id">
                <div v-if="item.id==scope.row.memberLevel">
                  {{ item.name}}
                </div>
                
              </div>
              <div v-if="scope.row.memberLevel==0">
                    无限制
                </div>
             </template>
            <!-- <template slot-scope="scope">
                {{ scope.row.memberLevel==0?"无限制":scope.row.memberLeve }}
            </template> -->
        </el-table-column>
        <el-table-column label="操作" width="250px" fixed="right">
        <template slot-scope="scope">
            <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.row)">编辑</el-button> 
            <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
        </el-table-column>
    </el-table>
    <!-- 页码组件开始 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[2,3,5,10,100, 200, 300, 400]"
      :page-size="pageSize"
      layout="total,sizes,prev,pager,next,jumper"
      :total="total">
    </el-pagination>
    <!-- 页码组件end -->

     <!--添加弹出框-->
            <el-dialog :title="title" :visible.sync="addFormVisible">
                    <el-form :model="form" :rules="rules" ref="form" :inline="true" label-width="200px">
                    <el-form-item label="店铺名" prop="shopId" required>
                    <el-select v-model="form.shopId" placeholder="请选择">
                        <el-option
                            v-for="item in testData"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="优惠券类型" prop="type" required>
                    <el-select v-model="form.type" placeholder="请选择">
                         <el-option
                            v-for="item in option1"    
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                      </el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="优惠券名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入优惠券名称"></el-input>
                    </el-form-item>
                    <el-form-item label="使用平台" prop="platform">
                        <el-select v-model="form.platform" placeholder="请选择">
                             <el-option
                                v-for="item in option2"    
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="数量" prop="count">
                        <el-input v-model.number="form.count" placeholder="输入数量"></el-input>
                    </el-form-item>
                    <el-form-item label="金额" prop="amount">
                        <el-input v-model.number="form.amount" placeholder="输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="每人限领张数" prop="perLimit">
                        <el-input v-model.number="form.perLimit" placeholder="输入每人限领张数"></el-input>
                    </el-form-item>
                    <el-form-item label="使用门槛" prop="minPoint">
                        <el-input v-model.number="form.minPoint" placeholder="输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="开始日期" prop="startTime">
                        <el-date-picker
                        v-model="form.startTime"
                        type="date"
                        placeholder="选择上线日期时间"
                        align="right"
                        :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束日期" prop="endTime">
                        <el-date-picker
                        v-model="form.endTime"
                        type="date"
                        placeholder="选择上线日期时间"
                        align="right"
                        :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="使用类型" prop="useType">
                        <el-select v-model="form.useType" placeholder="请选择">
                             <el-option
                                v-for="item in option2"    
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注" prop="note">
                        <el-input v-model="form.note" placeholder="输入备注"></el-input>
                    </el-form-item>
                     <el-form-item label="领取结束日期" prop="enableTime">
                        <el-date-picker
                        v-model="form.enableTime"
                        type="date"
                        placeholder="选择日期"
                        align="right"
                        :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="优惠码" prop="code">
                        <el-input v-model.number="form.code" placeholder="输入优惠码"></el-input>
                    </el-form-item>
                    <el-form-item label="可领取的会员类型" prop="memberLevel">
                        <el-select v-model="form.memberLevel" placeholder="请选择">
                            <el-option :label="option.name" :value="option.id"></el-option>
                            <el-option
                                v-for="item in testData2"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="addFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="add()">确 定</el-button>
                    </el-form-item>
                </el-form>
              </el-dialog>
    </div>
</template>
 <script>
    export default {
      data() {
        var number1=(rule, value, callback) => {
            if(value<1){
                return callback(new Error('不能小于1'))
            }else if(value>100000){
                return callback(new Error('不能大于100000'))
            }
        }
        var number2=(rule, value, callback) => {
            if(value<0){
                return callback(new Error('不能小于0'))
            }else if(value>100000){
                return callback(new Error('不能大于100000'))
            }
        }
        var startTime1=(rule, value, callback) => {
            let v=new Date(value).getTime();
            let s=new Date().getTime();
            if(v-s<-24*60*60*1000){
                return callback(new Error('不能选择今天以前'))
            }
        }  
        var endTime1=(rule, value, callback) => {
            let v=new Date(value).getTime();
            let s=new Date(this.form.startTime).getTime();
            if(this.form.startTime==null||this.form.startTime==''){
                return callback(new Error('请先选择开始时间'))
            }
            if(v-s<24*60*60*1000){
                return callback(new Error('请选择开始时间之后的时间'))
            }
        }
        var enableTime1=(rule, value, callback) => {
            let timestamp = new Date(value).getTime()
            let start  = new Date(this.form.startTime).getTime()
            let end = new Date(this.form.endTime).getTime()
            if(this.form.startTime==null||this.form.startTime==''){
                return callback(new Error('请先选择开始时间'))
            }
            if(this.form.endTime==null||this.form.startTime==''){
                return callback(new Error('请先选择结束时间'))
            }
            if (end < timestamp || timestamp < start+24*60*60*1000) {
                callback(new Error(`请在值班时间内选择`))
            }
        }
        return {
          tableData: [],
          testData:[],
          testData2:[],
          title:'',
          currentPage:1,//当前页面，默认1
          pageSize:5,//每页显示条数
          total:100,
          been:true,
          addFormVisible:false,
          form:{},
          option1:[
              {label:"全场赠券",value:0},
              {label:"会员赠券",value:1},
              {label:"消费赠券",value:2}, 
              {label:"注册赠券",value:3}
          ],
          option2:[
              { label:"通用" ,value:0},
              { label:"移动" ,value:1},
              { label:"PC" ,value:2 },
          ],
          option3:[
                {label:"全场通用", value:0},
                {label:"指定分类", value:1},
                {label:"指定车辆" ,value:2 }
          ],option:{
              name:"无门槛",id:0
          },formSearch: {},
            pickerOptions: {
            shortcuts: [{
                text: '今天',
                onClick(picker) {
                picker.$emit('pick', new Date());
                }
            }, {
                text: '昨天',
                onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
                }
            }, {
                text: '一周前',
                onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
                }
        }]
        },rules: {
            shopId: [
                { required: true, message: '请选择店铺名', trigger: ['change','blur'] }
            ],
            type: [
                { required: true, message: '请选择优惠券类型', trigger: 'change' }
            ],
            name: [
                { required: true, message: '请输入优惠券名称', trigger: 'blur' }
            ],
            platform:[
                { required: true, message: '请选择使用平台', trigger: ['change','blur'] }
            ],
            count:[
                { required: true, message: '数量不能为空'},
                { type: 'number', message: '数量必须为数字值'},
                 {validator: number1, trigger: ['change','blur']}
            ],
            amount:[
               { required: true, message: '不能为空'},
                { type: 'number', message: '必须为数字值'},
                 {validator: number1, trigger: ['change','blur']}
            ],
            perLimit:[
                { required: true, message: '不能为空'},
                { type: 'number', message: '必须为数字值'},
                  {validator: number1, trigger: ['change','blur']}
            ],
            minPoint:[
                { required: true, message: '不能为空'},
                { type: 'number', message: '必须为数字值'},
                {validator: number2, trigger: ['change','blur']}
            ],
            startTime:[
                {type: 'date', required: true, message: '请选择日期', trigger: 'change'},
                {validator: startTime1, trigger: ['change','blur']}
            ],
            endTime:[
                {type: 'date', required: true, message: '请选择时间', trigger: 'change'},
                {validator: endTime1, trigger: ['change','blur']}
            ],
            useType:[
                {required: true, message: '请选择使用类型', trigger: ['change','blur']}
            ],
            enableTime:[
                {type: 'date', required: true, message: '请选择时间', trigger: 'change'},
                {validator: enableTime1, trigger: ['change','blur']}
            ],
            code:[
                { required: true, message: '不能为空'},
                { type: 'number', message: '必须为数字值'},
            ],
            memberLevel:[
                {required: true, message: '请选择会员限制', trigger: ['change','blur']}
            ]
            }
        }
      },created:function(){
        this.loadData();
        this.testSite();
        this.testSite2();
            },
    methods: {
        loadData(){
          this.$http.post("/api/mks/coupon/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,
          {shopId:this.formSearch.shopId,type:this.formSearch.type
          ,name:this.formSearch.name,platform:this.formSearch.platform
          ,minPoint:this.formSearch.minPoint,startTime:this.formSearch.startTime,
          endTime:this.formSearch.endTime,useType:this.formSearch.useType}).then((response) => {
             if(response.data.code==2000){
               console.log(response.data)
                this.tableData = response.data.data.list;
                this.total = response.data.data.total;
              } 
        })        
    },testSite(){
        this.$http.post("/api/cars/shop/query").then((response) => {
          // console.log(response.data)
            if(response.data.code==2000){
              this.testData=response.data.data;
              // console.log(this.testData)
            } 
        })
    },testSite2(){
        this.$http.get("/api/mbs/memberLevel/queryAllByParam?pageNo=1&pageSize=10").then((response) => {
          // console.log(response.data)
            if(response.data.code==2000){
              this.testData2=response.data.data.list;
            //   console.log(this.testData2)
            } 
        })
    },handleSizeChange(val) {
                    // console.log(`每页 ${val} 条`);
                    this.pageSize=val;
                    this.loadData();
       },
     handleCurrentChange(val) {
              // console.log(`当前页: ${val}`);
              this.currentPage=val;
              this.loadData();
      },addbtn(){
        this.form={};
        this.title="添加";
        this.been=true;
        this.addFormVisible=true;
        // this.$refs.form.resetFields();
      },handleEdit(row){
        this.form=row;
        // console.log(this.form)
        this.title="修改";
        this.been=false;
        this.addFormVisible=true;
      }, add(){
                   var _this =this;
                   if(this.been){
                        this.$http.post("/api/mks/coupon/insert",this.form).then((response) => {
                        // console.log(response);
                    if(response.data.code==2000){
                        //提示成功
                        _this.$message({
                            type: 'success',
                            message: '添加成功!'
                        });
                        //关闭弹框
                        _this.addFormVisible=false;
                        //重新加载数据
                        _this.loadData();
                    }
                    }).catch(function (error) {
                            console.log(error);
                            this.$message.error("你错了。。。") 
                    })
                     
                  }else{
                    // this.form.status='';
                    console.log(this.form)
                     this.$http.put('/api/mks/coupon/update',this.form).then(function (response) {
                            console.log(response);
                            if(response.status == 200&&response.data.code==2000){
                                    //提示成功
                                   _this.$message({
                                        type: 'success',
                                        message:'修改成功!'
                                    });
                                    _this.loadData();
                                    }}
                        ).catch(function (error) {
                             console.log(error);
                            _this.$message.error("你错了。。。") 
                     })
                     this.addFormVisible=false;
                   } 
                 },
                 //删除
                 handleDelete(row){
                   this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                     confirmButtonText: '确定',
                     cancelButtonText: '取消',
                     type: 'warning'
                         }).then(() => {
                            //  console.log(row.id)
                             var _this=this;
                          this.$http.delete('/api/mks/coupon/deleteById?id='+row.id).then(function (response) {
                            console.log(response);
                            
                            if(response.status == 200&&response.data.code==2000){
                                    //提示成功
                                   _this.$message({
                                        type: 'success',
                                        message: '删除成功!'
                                    });
                                    _this.currentPage=1;
                                    _this.loadData();
                                    }}
                        ).catch(function (error) {
                            console.log(error);
                            this.$message.error("你错了。。。") 
          })   
                        }).catch(() => {
                            this.$message({
                             type: 'info',
                             message: '已取消删除'
                         });          
                     });
                     }
  },filters: {
        //时间格式处理
        dateFilter: function (data, format = "") {
            var dt = new Date(data);
            var y = dt.getFullYear();
            var m = (dt.getMonth()+1).toString().padStart(2,"0");
            var d = dt.getDate().toString().padStart(2,"0");
            var h = dt.getHours().toString().padStart(2,"0");
            var mm = dt.getMinutes().toString().padStart(2,"0");
            var s = dt.getSeconds().toString().padStart(2,"0");
            if (format.toLocaleLowerCase() === "yyyy-mm-dd" ||
                format.toLocaleLowerCase() === "") {
                return `${y}-${m}-${d}`;
            } else if (format.toLocaleLowerCase() === "yyyy/mm/dd") {
                return `${y}/${m}/${d}`;
            } else if (format.toLocaleLowerCase() === "yyyy-mm-dd hh:mm:ss") {
                return `${y}-${m}-${d} ${h}:${mm}:${s}`;
            } else if (format.toLocaleLowerCase() === "yyyy/mm/dd hh:mm:ss") {
                return `${y}/${m}/${d} ${h}:${mm}:${s}`;
            } else {
                return `输入的时间格式有误`;
            }
        },type:function(type){
           switch(type){
               case 0:
                   return '全场赠券';
                case 1:
                   return '会员赠券';
                case 2:
                   return '消费赠券';
                case 3:
                   return '注册赠券';
           }
        },platform:function(platform){
            switch(platform){
               case 0:
                   return '通用';
                case 1:
                   return '移动';
                case 2:
                   return 'PC';
           }
        },useType:function(useType){
             switch(useType){
               case 0:
                   return '全场通用';
                case 1:
                   return '指定分类';
                case 2:
                   return '指定车辆';
            }
        }
  }
}
 </script>       